const tryCatch = require('../../utils/tryCatch');
const JWT = require('jsonwebtoken');
const { JWTSECRET, EXPIRESIN } = require('../../config/index');
const { decrypt } = require('../../utils/crypto');
const { ServerFindUserAccount, ServerSetUserCount, ServerPasswordLogin, ServerGetUserInfo, ServerSerchUser, ServerUpdataUserInfo, ServerUpdateUserSignature, ServerFindUserByEmail, ServerUpdateUserPassword } = require("../../server/user/index");
const { sendVerificationEmail } = require('../../utils/emailSender');
const { generateVerifyCode, saveVerifyCode, verifyCode: validateCode } = require('../../utils/verifyCodeManager');
const UserInfo = require('../../model/userinfo');

const userController = {
    // 添加邮箱验证码相关方法
    sendEmailCode: tryCatch(async (req, res) => {
        const { email, type = 'update' } = req.body;

        if (!email) {
            return res.send({
                statusCode: 400,
                errorInfo: "邮箱地址不能为空",
                data: {}
            });
        }

        // 验证邮箱格式
        const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
        if (!emailPattern.test(email)) {
            return res.send({
                statusCode: 400,
                errorInfo: "邮箱格式不正确",
                data: {}
            });
        }

        // 生成验证码
        const code = generateVerifyCode();

        // 保存验证码
        saveVerifyCode(email, code, type);

        // 发送验证码邮件
        const sendResult = await sendVerificationEmail(email, code, type);

        if (sendResult.success) {
            res.send({
                statusCode: 200,
                message: "验证码已发送至邮箱",
                data: {}
            });
        } else {
            res.send({
                statusCode: 500,
                errorInfo: "该邮箱不可用",
                data: {}
            });
        }
    }),
    checkEmailCode: tryCatch(async (req, res) => {
        const { email, verifyCode, type = 'update' } = req.body;

        if (!email || !verifyCode) {
            return res.send({
                statusCode: 400,
                errorInfo: "邮箱地址和验证码不能为空",
                data: {}
            });
        }

        // 验证验证码
        const verification = validateCode(email, verifyCode, type);

        if (verification.valid) {
            res.send({
                statusCode: 200,
                message: "验证码验证成功",
                data: {}
            });
        } else {
            res.send({
                statusCode: 400,
                errorInfo: verification.message,
                data: {}
            });
        }
    }),
    // 添加其他控制器方法...
    userLogin: tryCatch(async (req, res) => {
        const { userAccount, password } = req.body
        let resPasswordLogin = await ServerPasswordLogin(userAccount, password)
        if (resPasswordLogin.isok) {
            const Authorization = 'Bearer' + ' ' + JWT.sign({ userAccount, password }, JWTSECRET, { expiresIn: EXPIRESIN })
            res.header("Authorization", Authorization)
            res.send({
                statusCode: 200,
                message: '登录成功',
                data: {}
            })
        } else {
            res.send({
                statusCode: 400,
                errorInfo: resPasswordLogin.message,
                data: {}
            })
        }

    }),
    userRegister: tryCatch(async (req, res) => {
        const { userAccount } = req.body
        let user = await ServerFindUserAccount(userAccount)
        if (user.isok) {
            res.send({
                statusCode: 402,
                errorInfo: "已有相同账号请换一个账号",
                data: {}
            })
        }
        let resSetUserCount = await ServerSetUserCount({ ...req.body })
        if (resSetUserCount.isok) {
            res.send({
                statusCode: 200,
                errorInfo: resSetUserCount.message,
                data: resSetUserCount.data
            })
        }
    }),
    userInfo: tryCatch(async (req, res) => {
        const { userAccount } = req.query;
        const getuserInfores = await ServerGetUserInfo(userAccount)
        if (getuserInfores.isok) {
            res.send({
                statusCode: 200,
                errorInfo: "获取成功",
                data: getuserInfores.data
            })
        } else {
            res.send({
                statusCode: 403,
                errorInfo: "获取失败",
                data: getuserInfores.data
            })
        }
    }),
    SerchUser: tryCatch(async (req, res) => {
        const keyword = req.body.keyword
        const userId = req.auth.userAccount
        const ServerGetUserInfores = await ServerGetUserInfo(userId)
        if (ServerGetUserInfores.isok) {
            const SerchUserres = await ServerSerchUser(keyword, ServerGetUserInfores.data.id)
            if (SerchUserres.isok) {
                res.send({
                    statusCode: 200,
                    errorInfo: "获取成功",
                    data: SerchUserres.data
                })
            } else {
                res.send({
                    statusCode: 200,
                    errorInfo: SerchUserres.message,
                    data: SerchUserres.data
                })
            }
        }
    }),
    UpdataUser: tryCatch(async (req, res) => {
        const {
            userid,
            avatar,
            username,
            sex,
            email,
            userSignature,
            verifyCode
        } = req.body;

        // 如果包含验证码，验证邮箱验证码
        if (email && verifyCode) {
            const verification = verifyCode(email, verifyCode, 'update');
            if (!verification.valid) {
                return res.send({
                    statusCode: 400,
                    errorInfo: verification.message,
                    data: {}
                });
            }
        }

        const ServerUpdataUserInfores = await ServerUpdataUserInfo({
            userid,
            avatar,
            username,
            sex,
            email,
            userSignature,
        });

        if (ServerUpdataUserInfores.isok) {
            res.send({
                statusCode: 200,
                message: "修改成功",
                data: ServerUpdataUserInfores.data
            });
        } else {
            res.send({
                statusCode: 400,
                errorInfo: ServerUpdataUserInfores.message,
                data: ServerUpdataUserInfores.data
            });
        }
    }),
    UpdateSignature: tryCatch(async (req, res) => {
        const { userId, userSignature } = req.body;

        const result = await ServerUpdateUserSignature(userId, userSignature);

        if (result.isok) {
            res.send({
                statusCode: 200,
                message: "更新签名成功",
                data: {}
            });
        } else {
            res.send({
                statusCode: 400,
                errorInfo: result.message || "更新签名失败",
                data: {}
            });
        }
    }),
    // 重置密码
    resetPassword: tryCatch(async (req, res) => {
        const { email, newPassword } = req.body;

        if (!email || !newPassword) {
            return res.send({
                statusCode: 400,
                errorInfo: "邮箱和新密码不能为空",
                data: {}
            });
        }

        try {
            // 根据邮箱查找用户
            const userResult = await ServerFindUserByEmail(email);

            if (!userResult.isok || !userResult.data) {
                return res.send({
                    statusCode: 404,
                    errorInfo: "未找到与该邮箱关联的账号",
                    data: {}
                });
            }

            const userAccount = userResult.data.userAccount;

            // 更新用户密码
            const updateResult = await ServerUpdateUserPassword(userAccount, newPassword);

            if (updateResult.isok) {
                res.send({
                    statusCode: 200,
                    message: "密码重置成功",
                    data: {
                        userAccount: userAccount,
                        password: newPassword
                    }
                });
            } else {
                res.send({
                    statusCode: 500,
                    errorInfo: updateResult.message || "密码重置失败",
                    data: {}
                });
            }
        } catch (error) {
            console.error("重置密码出错:", error);
            res.send({
                statusCode: 500,
                errorInfo: "服务器错误，请稍后重试",
                data: {}
            });
        }
    }),
    // 检查邮箱是否已被使用
    checkEmailExists: tryCatch(async (req, res) => {
        const { email, currentUserId } = req.body;

        if (!email) {
            return res.send({
                statusCode: 400,
                errorInfo: "邮箱地址不能为空",
                data: {}
            });
        }

        try {
            // 检查邮箱是否已被使用
            const result = await UserInfo.findOne({
                where: {
                    userMail: email
                },
                raw: true
            });

            // 如果找到了用户，且不是当前用户（修改自己的邮箱时）
            if (result && (!currentUserId || result.id != currentUserId)) {
                res.send({
                    statusCode: 409, // 冲突状态码
                    errorInfo: "该邮箱已被注册",
                    data: { exists: true }
                });
            } else {
                res.send({
                    statusCode: 200,
                    message: "邮箱可以使用",
                    data: { exists: false }
                });
            }
        } catch (error) {
            console.error("检查邮箱出错:", error);
            res.send({
                statusCode: 500,
                errorInfo: "服务器错误，请稍后重试",
                data: {}
            });
        }
    }),
}

module.exports = userController;// 引入User模型